package com.bootdo.cms.controller;

import cn.hutool.core.util.ObjectUtil;
import com.bootdo.cms.domain.MemberDO;
import com.bootdo.cms.service.MemberService;
import com.bootdo.common.annotation.Log;
import com.bootdo.common.utils.*;
import com.bootdo.system.domain.UserToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author KonBAI
 * @version 1.0
 * Create by 2019/12/16 20:22
 */
@Controller
@RequestMapping("/sign")
public class SignController {

    String prefix = "front";

    @Autowired
    private MemberService memberService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Log("进入登录/注册页面")
    @GetMapping("/login")
    public String login() {
        return prefix + "/sign";
    }

    @Log("登录")
    @PostMapping("/login")
    @ResponseBody
    R ajaxLogin(String username, String password, String verify, HttpServletRequest request) {

        try {
            //从session中获取随机数
            String random = (String) request.getSession().getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY);
            if (StringUtils.isBlank(verify)) {
                return R.error("请输入验证码");
            }
            if (random.equals(verify)) {
            } else {
                return R.error("请输入正确的验证码");
            }
        } catch (Exception e) {
            logger.error("验证码校验失败", e);
            return R.error("验证码校验失败");
        }
        password = MD5Utils.encrypt(username, password);
        UserToken token = new UserToken(username, password, "Member");
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            SessionUtils.setAttribute(request, "member", ShiroUtils.getMember());
            return R.ok("登录成功");
        } catch (AuthenticationException e) {
            return R.error("用户或密码错误");
        }
    }

    @Log("注册")
    @PostMapping("/register")
    @ResponseBody
    public R ajaxRegister(MemberDO member) {
        if (ObjectUtil.isNull(memberService.getByUsername(member.getUsername()))) {
            String encryptPassword = MD5Utils.encrypt(member.getUsername(), member.getPassword());
            member.setPassword(encryptPassword);
            member.setCreateBy(member.getUsername());
            if (memberService.save(member) > 0) {
                return R.ok("注册成功，请您登录！");
            } else {
                return R.error("注册失败");
            }
        }
        return R.error("此用户名已注册");
    }

    @Log("注销用户")
    @GetMapping("/logout")
    public String logOut(HttpServletRequest request) {
        ShiroUtils.logout();
        return "redirect:/front/index";
    }
}
